package cn.jd.org.service.impl;

import cn.jd.basic.config.BussinessException;
import cn.jd.basic.util.*;
import cn.jd.org.domain.Department;
import cn.jd.org.domain.Employee;
import cn.jd.org.domain.Shop;
import cn.jd.org.domain.ShopAuditLog;
import cn.jd.org.dto.ShopDto;
import cn.jd.org.mapper.EmployeeMapper;
import cn.jd.org.mapper.ShopAuditLogMapper;
import cn.jd.org.mapper.ShopMapper;
import cn.jd.org.query.ShopQuery;
import cn.jd.org.service.IShopService;
import cn.jd.basic.service.impl.BasicServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.StreamingHttpOutputMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jd
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BasicServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender sender;
    /**
     *  eacher页面商店状态数据的柱状图
     * */
    @Override
    public List<ShopDto> eacher() {
        return shopMapper.eacher();
    }
    /**
     * 分页查询加日志查询
     *
     * */
    @Override
    public PageList<Shop> queryByPageOrLog(ShopQuery query) {
        Integer count = shopMapper.count(query);
        List<Shop> shops = shopMapper.queryByPage(query);
        List<ShopAuditLog> shopAuditLogs = shopAuditLogMapper.findAll();


        // 用Stream流将集合转成map
        Map<Long, ShopAuditLog> collect = shopAuditLogs.stream().collect(Collectors.toMap(ShopAuditLog::getId, shop -> shop));
        for (Shop shop : shops) {
            System.out.println(shop);
            List<ShopAuditLog> byIds = shopAuditLogMapper.findByIds(shop.getId());
            System.out.println(byIds+"byIds");
            shop.setAuditLogs(byIds);
        }

        PageList<Shop> list = new PageList<>(count, shops );
        return list ;
    }

    @Override
    public void settlement(Shop shop) {
        // 校验店铺名称是否为空
        if(StringUtils.isEmpty(shop.getName())){
            throw new BussinessException("店铺名称不能为空，请重新输入店铺名称！！");
        }
        // 校验店铺名称是否合规
        Boolean aBoolean = BaiduAuditUtils.TextCensor(shop.getName());
        if(!aBoolean){
            throw new BussinessException("店铺名不合规请重新输入");
        }
        // 校验图片是否合规
        Boolean aBoolean1 = BaiduAuditUtils.ImgCensor(shop.getLogo());
            if(!aBoolean1){
                throw new BussinessException("图片不合规请，请审核后重新传入");
            }

        // 校验店铺是否存在
        Shop loadShop=shopMapper.loadByName(shop.getName());
        if(loadShop!=null){
            throw new BussinessException("店铺名已存在，请重新输入！！");
        }
        //判断管理员是否存在，且绑定的店铺
        Employee admin = shop.getAdmin();
        Employee employee = employeeMapper.loadUserName(admin.getName());
        if(employee!=null && employee.getShopId()!=null){
            throw new BussinessException("此用户已绑定店铺，请重新输入！！");
        }
        // 判断密码是否输入
        if("".equals(admin.getPassword().trim()) && admin.getPassword()==null){
            throw new BussinessException("密码不能为空，请重新输入！！");
        }
        // 判断前后两次密码是否一致
        if(!admin.getPassword().trim().equals(admin.getComfirmPassword().trim())) {
            System.out.println(admin.getPassword());
            System.out.println(admin.getComfirmPassword().trim());
            throw new BussinessException("两次密码不一致，请重新输入！！");
        }
        // 电话号码校验
        if(!checkTel(shop.getTel())){
            throw new BussinessException("请输入正确的电话格式");
        }
        Employee employee1 = new Employee();

        if(employee==null){
            employee1=admin;
            String password = employee1.getPassword();
            //获取研制
            String s = StrUtils.getRandomString(32);
            // 加密加盐
            String s1 = MD5Utils.encrypByMd5(password + s);
            employee1.setPassword(s1);
            employee1.setSalt(s);
            // 用户不存在添加用户
            employeeMapper.save(employee1);
        }
        // 设置店铺管理员
        shop.setAdminId(admin.getId());
        System.out.println(admin.getId());
        // 保存店铺信息
        shopMapper.save(shop);
        // 设置管理员的信息shopId
        admin.setShopId(shop.getId());
        // 修改员工信息
        employeeMapper.update(admin);

    }
    // 审核通过
    @Override
    public void auditPass(ShopAuditLog shopAuditLog)  {
       // 修改状态
        Shop shop = shopMapper.findById(shopAuditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        // 保存审核日志
        shopAuditLog.setAuditId(123L);
        shopAuditLog.setState(1L);
        shopAuditLogMapper.save(shopAuditLog);
        // 发送邮件
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper helper  = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1142153261@qq.com");
            helper.setSubject("店铺激活邮件");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>恭喜您审核您审核通过，点击下方链接激活店铺</h1>"+
                    "http://localhost:8080/shop/active/"+shopAuditLog.getShopId(),true);
          /*  // 4.添加附件
            helper.addAttachment("好东西.jpg",new File("C:\\Users\\lenovo\\Desktop\\1.jpg"));*/
           // 4.设置收件人
            helper.setTo("1142153261@qq.com");
        } catch (MessagingException e) {
            throw new BussinessException("发送邮件错误！");
        }
        // 6.发送邮件
        sender.send(mimeMessage);

    }
/*驳回*/
    @Override
    public void auditReject(ShopAuditLog shopAuditLog) {
    // 修改状态
        Shop shop = shopMapper.findById(shopAuditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        // 保存审核日志
        shopAuditLog.setAuditId(123L);
        shopAuditLog.setState(0L);
        shopAuditLogMapper.save(shopAuditLog);
        // 发送邮件
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper helper  = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1142153261@qq.com");
            helper.setSubject("店铺激活失败");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>你的店铺审核失败，请重新修改信息</h1>"+
                    "http://localhost:8081/#/registerAgain/"+shopAuditLog.getShopId(),true);
         /* // 4.添加附件
            helper.addAttachment("好东西.jpg",new File("C:\\Users\\lenovo\\Desktop\\1.jpg"));*/
            // 4.设置收件人
            helper.setTo("1142153261@qq.com");
        } catch (MessagingException e) {
            throw new BussinessException("发送邮件错误！");
        }
        // 6.发送邮件
        sender.send(mimeMessage);

    }
    /*商家激活*/
    @Override
    public void active(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    /**
     * 批量添加
     * @param shops
     */
    @Override
    public void importExcel(List<Shop> shops) {
        shopMapper.importExcel(shops);
    }




    /*
    * 电话号码校验
    */
    private static Boolean checkTel(String tel) {

        //编译正则表达式
        String reg ="^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$" ;

        return tel.matches(reg)?true:false;
    }

    public static void main(String[] args) {
        //获取研制
        String s = StrUtils.getRandomString(32);
        System.out.println(s);
        String password="1";
        // 加密加盐
        String s1 = MD5Utils.encrypByMd5(password + s);
        System.out.println(s1);
    }
}
